var debug = 'dev' //dev test pro
var host,hostName
var appid = ''
debug = debug=='pro' || debug=='test'?false:true //debug模式
if (debug) {
    // #ifdef APP
    hostName = "http://hktest.goodw.cn"
    host = hostName + "/api.php?application=app&application_client_type=weixin&s=";
    // #endif
    // #ifdef MP
    hostName = "http://company.goodw.cn"
    // hostName = "/api";
    host = hostName + "/api.php?application=app&application_client_type=weixin&s=";
    // #endif
    // #ifdef H5
    hostName = "/api";
    host = hostName + "/api.php?application=app&application_client_type=weixin&s=";
    // #endif

} else {
    // #ifdef APP
    hostName = "https://h5.xxx.com";
    host = hostName + "/api.php?application=app&application_client_type=weixin&s=";
    // #endif
    // #ifdef MP 
    hostName = "https://api.goodw.cn";
    host = hostName + "/api.php?application=app&application_client_type=weixin&s=";
    // #endif
    // #ifdef H5
    hostName = "/api";
    host = hostName + "/api.php?application=app&application_client_type=weixin&s=";
    // #endif
}

// #ifdef H5
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return false;
}
// #endif
const api = {
    wx:{
        config:hostName + '/index.php/wechat/getJssdkConfig',//微信配置
        authUrl:hostName + '/index.php/wechat/getAuthUrl',//登录
        authLogin:hostName + '/index.php/wechat/getAuthByCode'
    },
    user:{
        info:hostName + '/index.php/huike.order/getStoreInfo'
    }
}
var app = getApp()
const request = function(url = '', data = {}, method = 'POST', token=true) {
    return new Promise((resolve, reject) => {
        let that = this
        let lastUrl = url
        data.code = getQueryVariable('code')
        // let lastUrl = that.globalData.loginInfo&&token  ? url + '&token=' + that.globalData.loginInfo.token : url;
        uni.request({
            header: {
                'Content-Type': 'application/json;charset=UTF-8',
                'accept': '*/*',
            },
            method: method,
            url: lastUrl,
            data: data,
            dataType: 'json',
            success(res) {
                if (res.data.code == 0) {
                    resolve(res.data)
                } else if (res.data.code == 100) {
                    uni.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        duration: 3000
                    })
                } else if (res.data.code == -400) {
                    uni.showModal({
                        title: '登录状态已过期，请重新登录！',
                        showCancel: false,
                        success(res) {
                           
                        }
                    })
                } else {
                    uni.showToast({
                        title: res.data.msg,
                        icon: 'none'
                    })
                }
            },
            fail(res) {
                uni.hideLoading()
                reject(res.data)
            }
        })
    })
}

const uploadFile = function(url, filePath, name = 'file', formData = {}, token=false) {
    return new Promise((resolve, reject) => {
        let that = this;
        let lastUrl = that.globalData.loginInfo&&token ? url + '&token=' + that.globalData.loginInfo.token : url;
        let a = uni.uploadFile({
            url: lastUrl, // 仅为示例，非真实的接口地址
            filePath: filePath,
            name: name,
            success: (res) => {
                let data = JSON.parse(res.data)
                if (data.code == 0) {
                    resolve(data.data.url)
                } else {
                    uni.showToast({
                        title: "上传失败",
                        icon: "none"
                    })
                    reject(data.msg);
                }
            },
            fail: (err) => {
                console.log(err);
            }
        });
    })
}
// 微信支付
/**
 * timeStamp {Str} 时间戳
 * nonceStr {Str} 随机字符串
 * package {Str} 统一下单接口返回的 prepay_id 参数值
 * signType {Str} 签名算法
 * paySign {Str} 签名
 * completeFun {Fun} 结束回调
 * */
const wx_pay = function(res) {
    return new Promise((resolve, reject) => {
        uni.requestPayment({
            provider: 'wxpay',
            // #ifdef MP
            orderInfo: "orderInfo",
            timeStamp: res.timestamp,
            nonceStr: res.noncestr,
            package: res.package,
            signType: res.signType,
            paySign: res.sign,
            // #endif
            // #ifdef APP
            orderInfo: JSON.stringify({
                "appid": res.appid,
                "noncestr": res.noncestr,
                "package": "Sign=WXPay",
                "partnerid": res.partnerid,
                "prepayid": res.prepayid,
                "timestamp": res.timestamp,
                "sign": res.sign
            }),
            // #endif
            success(res) {
                resolve(true);
            },
            fail(err) {
                reject(err);
            },
        });
    })
}
const login = function() {

    return new Promise((resolve, reject) => {
        let that = this
        // #ifdef H5
        that.$request(that.$api.login, {
            authcode: "0e3KGp000MSfeS1ALm100qbkaj2KGp0c"
        }, 'POST').then(res => {
            console.log('request', res)
            if (res.code == 0) {
                uni.showToast({
                    title: '登录成功',
                    icon: 'none'
                })
                that.$u.vuex('vuex_token', res.data.token);
                that.$u.vuex('vuex_userInfo', res.data);
                resolve(res.data);
            }
        }).catch(err => {
            console.log('err', err)
            reject(err)
        })
        // #endif
        // #ifdef MP
        uni.getUserProfile({
            lang: 'zh_CN',
            desc: '用于显示您的昵称和头像', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (info) => {
                console.log(info);
                uni.showLoading({
                    title: '登录中...',
                    mask: true
                })
                uni.login({
                    success(e) {
                        console.log('code:', e.code)
                        // return false;
                        that.$request(that.$api.login, {
                            authcode: e.code
                        }, 'POST').then(res => {
                            console.log('request', res)
                            if (res.code == 0) {
                                uni.showToast({
                                    title: '登录成功',
                                    icon: 'none'
                                })
                                that.$u.vuex('vuex_token', res.data.token);
                                that.$u.vuex('vuex_userInfo', res.data)
                                resolve(res.data);
                            }
                        }).catch(err => {
                            console.log('err', err)
                            uni.showToast({
                                title: '登录失败！',
                                icon: 'none'
                            })
                            reject(err)
                        })
                        uni.hideLoading()
                    },
                    fail() {
                        uni.showToast({
                            title: '登录失败',
                            icon: 'none'
                        })
                    },
                    complete() {
                        //uni.hideLoading()
                    }
                })
            },
            fail(err) {
                console.log(err);
                uni.showToast({
                    title: '获取用户授权失败',
                    icon: 'none'
                })
                reject(false)
            }
        })
        // #endif
    })
};
const webLogin = function(e) {
    let that = this
    uni.request(that.$api.wx.authLogin, {
        code: e,
        callback:encodeURIComponent(window.location.href)
    }, 'GET').then(res => {
        console.log('res',res)
        if (res.code == 0) {
            uni.setStorageSync('userInfo',res.data)
            return res.data;
        } else {
            return false
        }
    }).catch(err => {
        console.log('err', err)
    })
};

const formatDate = function(date = new Date(), format) {
    const year = date.getFullYear();
    const month = ("0" + (date.getMonth() + 1)).slice(-2); // 月份从0开始，需要+1，并补零
    const day = ("0" + date.getDate()).slice(-2); // 补零处理
    const hours = ("0" + date.getHours()).slice(-2);
    const minutes = ("0" + date.getMinutes()).slice(-2);
    const seconds = ("0" + date.getSeconds()).slice(-2);
    let res = ""
    switch (format) {
        case 1:
            res = `${year}-${month}-${day}`;
            break;
        case 2:
            res = `${month}-${day}`;
            break;
        case 3:
            res = `${hours}:${minutes}:${seconds}`
            break;
        case 4:
            res = `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
            break;
        case 5:
            res = `${year}年${month}月${day}日 ${hours}:${minutes}`
            break;
        case 6:
            res = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
            break;
        case 7:
            res = `${year}${month}${day} ${hours}:${minutes}`
            break;
        case 8:
            res = `${year}${month}${day}`
            break;
        default:
            res = `${year}-${month}-${day} ${hours}:${minutes}`;
            break;
    }
    return res
}
export {
    request,
    login,
    webLogin,
    api,
    host,
    hostName,
    debug,
    wx_pay,
    formatDate
}